#include <sdk.h>
#include "parserthreadedtask.h"
#include "cclogger.h"
#include "parser.h"
#include "tokentree.h"

#define CC_PARSERTHREADEDTASK_DEBUG_OUTPUT 0

ParserThreadedTask::ParserThreadedTask( Parser* parser, wxMutex& parserMTX ) :
  m_Parser( parser ),
  m_ParserMutex( parserMTX ) {
}

int ParserThreadedTask::Execute() {
  if( !m_Parser ) {
    return 0;
  }
  CC_LOCKER_TRACK_P_MTX_LOCK( m_ParserMutex )
  wxString   preDefs( m_Parser->m_PredefinedMacros );
  StringList batchFiles( m_Parser->m_BatchParseFiles );
  CC_LOCKER_TRACK_P_MTX_UNLOCK( m_ParserMutex );
  if( !preDefs.IsEmpty() ) {
    m_Parser->ParseBuffer( preDefs, false, false );
  }
  m_Parser->ClearPredefinedMacros();
  if( m_Parser->m_IgnoreThreadEvents ) {
    m_Parser->m_IsFirstBatch = true;
  }
  while( !batchFiles.empty() ) {
    m_Parser->Parse( batchFiles.front() );
    batchFiles.pop_front();
  }
  CC_LOCKER_TRACK_P_MTX_LOCK( m_ParserMutex )
  m_Parser->m_BatchParseFiles.clear();
  if( m_Parser->m_IgnoreThreadEvents ) {
    m_Parser->m_IgnoreThreadEvents = false;
    m_Parser->m_IsParsing = true;
  }
  CC_LOCKER_TRACK_P_MTX_UNLOCK( m_ParserMutex );
  return 0;
}

MarkFileAsLocalThreadedTask::MarkFileAsLocalThreadedTask( Parser* parser, M_Code_Project* project ) :
  m_Parser( parser ), m_Project( project ) {
}

int MarkFileAsLocalThreadedTask::Execute() {
  if( !m_Project ) {
    return 0;
  }
  if( !m_Parser ) {
    return 0;
  }
  for( FilesList::const_iterator it  = m_Project->GetFilesList().begin();
       it != m_Project->GetFilesList().end(); ++it ) {
    ProjectFile* pf = *it;
    if( !pf ) {
      continue;
    }
    if( ParserCommon::FileType( pf->relativeFilename ) != ParserCommon::ftOther ) {
      TokenTree* tree = m_Parser->GetTokenTree();
      CC_LOCKER_TRACK_TT_MTX_LOCK( s_TokenTreeMutex )
      tree->MarkFileTokensAsLocal( pf->file.GetFullPath(), true, m_Project );
      CC_LOCKER_TRACK_TT_MTX_UNLOCK( s_TokenTreeMutex )
    }
  }
  return 0;
}
